<!DOCTYPE HTML>
<html lang="en-US" manifest="../manifest.appcache">
    
    <head prefix="og: http://ogp.me/ns# book: http://ogp.me/ns/book#">
        
        
        <meta charset="UTF-8">
        <title>《The Swift Programming Language》中文版</title>

        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="robots" content="index, follow">
        <meta name="author" content="">
        <meta name="description" content="Swift 中文翻译组：364279588（要求对翻译感兴趣）">
        <meta name="keywords" content="gitbook,github" >
        <meta name="generator" content="www.gitbook.io">

        
        <link rel="next" href="../chapter2/chapter2.html" />
        
        
        <link rel="prev" href="../chapter1/01_swift.html" />
        

        <meta property="og:title" content="Swift 初见 | The Swift Programming Language 中文版">
        <meta property="og:site_name" content="The Swift Programming Language 中文版">
        <meta property="og:type" content="book">
        <meta property="og:locale" content="en_US">

        <meta property="book:author" content="https://github.com/">
        <meta property="book:tag" content="GitBook">

        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">

        <link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">
        
        
    </head>
    <body>
        
        

        <link rel="stylesheet" href="../gitbook/style.css">
        


        
    <div class="book"  data-level="1.2" data-basepath=".." data-revision="1402634093001">
    <div class="book-header">
    <!-- Actions Left -->
    <a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
    
    <a href="https://github.com/null" target="_blank" class="btn pull-left home-bookmark" aria-label="GitHub home"><i class="fa fa-bookmark-o"></i></a>
    
    <a href="#" class="btn pull-left toggle-search" aria-label="Toggle search"><i class="fa fa-search"></i></a>
    <span id="font-settings-wrapper">
        <a href="#" class="btn pull-left toggle-font-settings" aria-label="Toggle font settings"><i class="fa fa-font"></i>
        </a>
        <div class="dropdown-menu font-settings">
    <div class="dropdown-caret">
        <span class="caret-outer"></span>
        <span class="caret-inner"></span>
    </div>

    <div class="btn-group btn-block">
        <button id="reduce-font-size" class="btn btn-default">A</button>
        <button id="enlarge-font-size" class="btn btn-default">A</button>
    </div>

    <ul class="list-group font-family-list">
        <li class="list-group-item" data-font="0">Serif</li>
        <li class="list-group-item" data-font="1">Sans</li>
    </ul>

    <div class="btn-group btn-group-xs btn-block color-theme-list">
        <button type="button" class="btn btn-default" id="color-theme-preview-0" data-theme="0">White</button>
        <button type="button" class="btn btn-default" id="color-theme-preview-1" data-theme="1">Sepia</button>
        <button type="button" class="btn btn-default" id="color-theme-preview-2" data-theme="2">Night</button>
    </div>
</div>

    </span>

    <!-- Actions Right -->
    
    <a href="#" target="_blank" class="btn pull-right google-plus-sharing-link sharing-link" data-sharing="google-plus" aria-label="Share on Google Plus"><i class="fa fa-google-plus"></i></a>
    
    
    <a href="#" target="_blank" class="btn pull-right facebook-sharing-link sharing-link" data-sharing="facebook" aria-label="Share on Facebook"><i class="fa fa-facebook"></i></a>
    
    
    <a href="#" target="_blank" class="btn pull-right twitter-sharing-link sharing-link" data-sharing="twitter" aria-label="Share on Twitter"><i class="fa fa-twitter"></i></a>
    

    

    <!-- Title -->
    <h1>
        <i class="fa fa-spinner fa-spin"></i>
        <a href="../" >The Swift Programming Language 中文版</a>
    </h1>
</div>

    

<div class="book-summary">
    <div class="book-search">
        <input type="text" placeholder="Search" class="form-control" />
    </div>
    <ul class="summary">
        
        

        

        

        

        <li data-level="0" data-path="index.html">
            <a href="../"><i class="fa fa-check"></i> 序</a>
        </li>
        
    
        <li class="chapter " data-level="1" data-path="chapter1/chapter1.html">
            
            <a href="../chapter1/chapter1.html">
                <i class="fa fa-check"></i> <b>1.</b> 欢迎使用 Swift
            </a>
            
            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.1" data-path="chapter1/01_swift.html">
            
            <a href="../chapter1/01_swift.html">
                <i class="fa fa-check"></i> <b>1.1.</b> 关于 Swift
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="1.2" data-path="chapter1/02_a_swift_tour.html">
            
            <a href="../chapter1/02_a_swift_tour.html">
                <i class="fa fa-check"></i> <b>1.2.</b> Swift 初见
            </a>
            
            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="2" data-path="chapter2/chapter2.html">
            
            <a href="../chapter2/chapter2.html">
                <i class="fa fa-check"></i> <b>2.</b> Swift 教程
            </a>
            
            
            <ul class="articles">
                
    
        <li class="chapter " data-level="2.1" data-path="chapter2/01_The_Basics.html">
            
            <a href="../chapter2/01_The_Basics.html">
                <i class="fa fa-check"></i> <b>2.1.</b> 基础部分
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.2" data-path="chapter2/02_Basic_Operators.html">
            
            <a href="../chapter2/02_Basic_Operators.html">
                <i class="fa fa-check"></i> <b>2.2.</b> 基本运算符
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.3" data-path="chapter2/03_Strings_and_Characters.html">
            
            <a href="../chapter2/03_Strings_and_Characters.html">
                <i class="fa fa-check"></i> <b>2.3.</b> 字符串和字符
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.4" data-path="chapter2/04_Collection_Types.html">
            
            <a href="../chapter2/04_Collection_Types.html">
                <i class="fa fa-check"></i> <b>2.4.</b> 集合类型
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.5" data-path="chapter2/05_Control_Flow.html">
            
            <a href="../chapter2/05_Control_Flow.html">
                <i class="fa fa-check"></i> <b>2.5.</b> 控制流
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.6" data-path="chapter2/06_Functions.html">
            
            <a href="../chapter2/06_Functions.html">
                <i class="fa fa-check"></i> <b>2.6.</b> 函数
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.7" data-path="chapter2/07_Closures.html">
            
            <a href="../chapter2/07_Closures.html">
                <i class="fa fa-check"></i> <b>2.7.</b> 闭包
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.8" data-path="chapter2/08_Enumerations.html">
            
            <a href="../chapter2/08_Enumerations.html">
                <i class="fa fa-check"></i> <b>2.8.</b> 枚举
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.9" data-path="chapter2/09_Classes_and_Structures.html">
            
            <a href="../chapter2/09_Classes_and_Structures.html">
                <i class="fa fa-check"></i> <b>2.9.</b> 类和结构体
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.10" data-path="chapter2/10_Properties.html">
            
            <a href="../chapter2/10_Properties.html">
                <i class="fa fa-check"></i> <b>2.10.</b> 属性
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.11" data-path="chapter2/11_Methods.html">
            
            <a href="../chapter2/11_Methods.html">
                <i class="fa fa-check"></i> <b>2.11.</b> 方法
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.12" data-path="chapter2/12_Subscripts.html">
            
            <a href="../chapter2/12_Subscripts.html">
                <i class="fa fa-check"></i> <b>2.12.</b> 附属脚本
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.13" data-path="chapter2/13_Inheritance.html">
            
            <a href="../chapter2/13_Inheritance.html">
                <i class="fa fa-check"></i> <b>2.13.</b> 继承
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.14" data-path="chapter2/14_Initialization.html">
            
            <a href="../chapter2/14_Initialization.html">
                <i class="fa fa-check"></i> <b>2.14.</b> 构造过程
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.15" data-path="chapter2/15_Deinitialization.html">
            
            <a href="../chapter2/15_Deinitialization.html">
                <i class="fa fa-check"></i> <b>2.15.</b> 析构过程
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.16" data-path="chapter2/16_Automatic_Reference_Counting.html">
            
            <a href="../chapter2/16_Automatic_Reference_Counting.html">
                <i class="fa fa-check"></i> <b>2.16.</b> 自动引用计数
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.17" data-path="chapter2/17_Optional_Chaining.html">
            
            <a href="../chapter2/17_Optional_Chaining.html">
                <i class="fa fa-check"></i> <b>2.17.</b> 可选链
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.18" data-path="chapter2/18_Type_Casting.html">
            
            <a href="../chapter2/18_Type_Casting.html">
                <i class="fa fa-check"></i> <b>2.18.</b> 类型检查
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.19" data-path="chapter2/19_Nested_Types.html">
            
            <a href="../chapter2/19_Nested_Types.html">
                <i class="fa fa-check"></i> <b>2.19.</b> 类型嵌套
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.20" data-path="chapter2/20_Extensions.html">
            
            <a href="../chapter2/20_Extensions.html">
                <i class="fa fa-check"></i> <b>2.20.</b> 扩展
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.21" data-path="chapter2/21_Protocols.html">
            
            <a href="../chapter2/21_Protocols.html">
                <i class="fa fa-check"></i> <b>2.21.</b> 协议
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.22" data-path="chapter2/22_Generics.html">
            
            <a href="../chapter2/22_Generics.html">
                <i class="fa fa-check"></i> <b>2.22.</b> 泛型
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="2.23" data-path="chapter2/23_Advanced_Operators.html">
            
            <a href="../chapter2/23_Advanced_Operators.html">
                <i class="fa fa-check"></i> <b>2.23.</b> 高级操作符
            </a>
            
            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="3" data-path="chapter3/chapter3.html">
            
            <a href="../chapter3/chapter3.html">
                <i class="fa fa-check"></i> <b>3.</b> 语言参考
            </a>
            
            
            <ul class="articles">
                
    
        <li class="chapter " data-level="3.1" data-path="chapter3/01_About_the_Language_Reference.html">
            
            <a href="../chapter3/01_About_the_Language_Reference.html">
                <i class="fa fa-check"></i> <b>3.1.</b> 关于语言参考
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="3.2" data-path="chapter3/02_Lexical_Structure.html">
            
            <a href="../chapter3/02_Lexical_Structure.html">
                <i class="fa fa-check"></i> <b>3.2.</b> 词法结构
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="3.3" data-path="chapter3/03_Types.html">
            
            <a href="../chapter3/03_Types.html">
                <i class="fa fa-check"></i> <b>3.3.</b> 类型
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="3.4" data-path="chapter3/04_Expressions.html">
            
            <a href="../chapter3/04_Expressions.html">
                <i class="fa fa-check"></i> <b>3.4.</b> 表达式
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="3.5" data-path="chapter3/10_Statements.html">
            
            <a href="../chapter3/10_Statements.html">
                <i class="fa fa-check"></i> <b>3.5.</b> 语句
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="3.6" data-path="chapter3/05_Declarations.html">
            
            <a href="../chapter3/05_Declarations.html">
                <i class="fa fa-check"></i> <b>3.6.</b> 声明
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="3.7" data-path="chapter3/06_Attributes.html">
            
            <a href="../chapter3/06_Attributes.html">
                <i class="fa fa-check"></i> <b>3.7.</b> 特性
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="3.8" data-path="chapter3/07_Patterns.html">
            
            <a href="../chapter3/07_Patterns.html">
                <i class="fa fa-check"></i> <b>3.8.</b> 模式
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="3.9" data-path="chapter3/08_Generic_Parameters_and_Arguments.html">
            
            <a href="../chapter3/08_Generic_Parameters_and_Arguments.html">
                <i class="fa fa-check"></i> <b>3.9.</b> 泛型参数
            </a>
            
            
        </li>
    
        <li class="chapter " data-level="3.10" data-path="chapter3/09_Summary_of_the_Grammar.html">
            
            <a href="../chapter3/09_Summary_of_the_Grammar.html">
                <i class="fa fa-check"></i> <b>3.10.</b> 语法总结
            </a>
            
            
        </li>
    

            </ul>
            
        </li>
    


        
        <li class="divider"></li>
        <li>
            <a href="http://www.gitbook.io/" target="blank" class="gitbook-link">Generated using GitBook</a>
        </li>
<li style="margin-left:15%;"> <iframe  src="http://ghbtns.com/github-btn.html?user=numbbbbb&repo=the-swift-programming-language-in-chinese&type=watch&count=true&size=large"
  allowtransparency="true" frameborder="0" scrolling="0" width="170" height="30"></iframe></li><li><p style="padding-left:5px;padding-right:5px;">翻译无任何商业目的，仅供内部学习交流使用！</p></li><li><script src="http://s19.cnzz.com/z_stat.php?id=1000480711&web_id=1000480711" language="JavaScript"></script></li>        
    </ul>
</div>

    <div class="book-body">
        <div class="body-inner">
            <div class="page-wrapper" tabindex="-1">
                <div class="book-progress">
    <div class="bar">
        <div class="inner" style="width: 7.894736842105263%;min-width: 5.2631578947368425%;"></div>
    </div>
    <div class="chapters">
    
        <a href="../index.html" title="Introduction" class="chapter done new-chapter" data-progress="0" style="left: 0%;"></a>
    
        <a href="../chapter1/chapter1.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 2.6315789473684212%;"></a>
    
        <a href="../chapter1/01_swift.html" title="关于 Swift" class="chapter done " data-progress="1.1" style="left: 5.2631578947368425%;"></a>
    
        <a href="../chapter1/02_a_swift_tour.html" title="Swift 初见" class="chapter done " data-progress="1.2" style="left: 7.894736842105263%;"></a>
    
        <a href="../chapter2/chapter2.html" title="Swift 教程" class="chapter  new-chapter" data-progress="2" style="left: 10.526315789473685%;"></a>
    
        <a href="../chapter2/01_The_Basics.html" title="基础部分" class="chapter  " data-progress="2.1" style="left: 13.157894736842104%;"></a>
    
        <a href="../chapter2/10_Properties.html" title="属性" class="chapter  " data-progress="2.10" style="left: 15.789473684210526%;"></a>
    
        <a href="../chapter2/11_Methods.html" title="方法" class="chapter  " data-progress="2.11" style="left: 18.42105263157895%;"></a>
    
        <a href="../chapter2/12_Subscripts.html" title="附属脚本" class="chapter  " data-progress="2.12" style="left: 21.05263157894737%;"></a>
    
        <a href="../chapter2/13_Inheritance.html" title="继承" class="chapter  " data-progress="2.13" style="left: 23.68421052631579%;"></a>
    
        <a href="../chapter2/14_Initialization.html" title="构造过程" class="chapter  " data-progress="2.14" style="left: 26.31578947368421%;"></a>
    
        <a href="../chapter2/15_Deinitialization.html" title="析构过程" class="chapter  " data-progress="2.15" style="left: 28.94736842105263%;"></a>
    
        <a href="../chapter2/16_Automatic_Reference_Counting.html" title="自动引用计数" class="chapter  " data-progress="2.16" style="left: 31.57894736842105%;"></a>
    
        <a href="../chapter2/17_Optional_Chaining.html" title="可选链" class="chapter  " data-progress="2.17" style="left: 34.21052631578947%;"></a>
    
        <a href="../chapter2/18_Type_Casting.html" title="类型检查" class="chapter  " data-progress="2.18" style="left: 36.8421052631579%;"></a>
    
        <a href="../chapter2/19_Nested_Types.html" title="类型嵌套" class="chapter  " data-progress="2.19" style="left: 39.473684210526315%;"></a>
    
        <a href="../chapter2/02_Basic_Operators.html" title="基本运算符" class="chapter  " data-progress="2.2" style="left: 42.10526315789474%;"></a>
    
        <a href="../chapter2/20_Extensions.html" title="扩展" class="chapter  " data-progress="2.20" style="left: 44.73684210526316%;"></a>
    
        <a href="../chapter2/21_Protocols.html" title="协议" class="chapter  " data-progress="2.21" style="left: 47.36842105263158%;"></a>
    
        <a href="../chapter2/22_Generics.html" title="泛型" class="chapter  " data-progress="2.22" style="left: 50%;"></a>
    
        <a href="../chapter2/23_Advanced_Operators.html" title="高级操作符" class="chapter  " data-progress="2.23" style="left: 52.63157894736842%;"></a>
    
        <a href="../chapter2/03_Strings_and_Characters.html" title="字符串和字符" class="chapter  " data-progress="2.3" style="left: 55.26315789473684%;"></a>
    
        <a href="../chapter2/04_Collection_Types.html" title="集合类型" class="chapter  " data-progress="2.4" style="left: 57.89473684210526%;"></a>
    
        <a href="../chapter2/05_Control_Flow.html" title="控制流" class="chapter  " data-progress="2.5" style="left: 60.526315789473685%;"></a>
    
        <a href="../chapter2/06_Functions.html" title="函数" class="chapter  " data-progress="2.6" style="left: 63.1578947368421%;"></a>
    
        <a href="../chapter2/07_Closures.html" title="闭包" class="chapter  " data-progress="2.7" style="left: 65.78947368421052%;"></a>
    
        <a href="../chapter2/08_Enumerations.html" title="枚举" class="chapter  " data-progress="2.8" style="left: 68.42105263157895%;"></a>
    
        <a href="../chapter2/09_Classes_and_Structures.html" title="类和结构体" class="chapter  " data-progress="2.9" style="left: 71.05263157894737%;"></a>
    
        <a href="../chapter3/chapter3.html" title="语言参考" class="chapter  new-chapter" data-progress="3" style="left: 73.6842105263158%;"></a>
    
        <a href="../chapter3/01_About_the_Language_Reference.html" title="关于语言参考" class="chapter  " data-progress="3.1" style="left: 76.3157894736842%;"></a>
    
        <a href="../chapter3/09_Summary_of_the_Grammar.html" title="语法总结" class="chapter  " data-progress="3.10" style="left: 78.94736842105263%;"></a>
    
        <a href="../chapter3/02_Lexical_Structure.html" title="词法结构" class="chapter  " data-progress="3.2" style="left: 81.57894736842105%;"></a>
    
        <a href="../chapter3/03_Types.html" title="类型" class="chapter  " data-progress="3.3" style="left: 84.21052631578948%;"></a>
    
        <a href="../chapter3/04_Expressions.html" title="表达式" class="chapter  " data-progress="3.4" style="left: 86.84210526315789%;"></a>
    
        <a href="../chapter3/10_Statements.html" title="语句" class="chapter  " data-progress="3.5" style="left: 89.47368421052632%;"></a>
    
        <a href="../chapter3/05_Declarations.html" title="声明" class="chapter  " data-progress="3.6" style="left: 92.10526315789474%;"></a>
    
        <a href="../chapter3/06_Attributes.html" title="特性" class="chapter  " data-progress="3.7" style="left: 94.73684210526316%;"></a>
    
        <a href="../chapter3/07_Patterns.html" title="模式" class="chapter  " data-progress="3.8" style="left: 97.36842105263158%;"></a>
    
        <a href="../chapter3/08_Generic_Parameters_and_Arguments.html" title="泛型参数" class="chapter  " data-progress="3.9" style="left: 100%;"></a>
    
    </div>
</div>

                <div class="page-inner">
                
                    <section class="normal" id="section-gitbook_6">
                    
                        <blockquote>
<p>翻译：numbbbbb
校对：shinyzhu</p>
</blockquote>
<h1 id="swift-">Swift 初见</h1>
<hr>
<p>本页内容包括：</p>
<ul>
<li><a href="#simple_values">简单值（Simple Values）</a></li>
<li><a href="#control_flow">控制流（Control Flow）</a></li>
<li><a href="#functions_and_closures">函数和闭包（Functions and Closures）</a></li>
<li><a href="#objects_and_classes">对象和类（Objects and Classes）</a></li>
<li><a href="#enumerations_and_structures">枚举和结构体（Enumerations and Structures）</a></li>
<li><a href="#protocols_and_extensions">接口和扩展（Protocols and Extensions）</a></li>
<li><a href="#generics">泛型（Generics）</a></li>
</ul>
<p>通常来说，编程语言教程中的第一个程序应该在屏幕上打印“Hello, world”。在 Swift 中，可以用一行代码实现：</p>
<pre><code class="lang-swift">    println(&quot;Hello, world&quot;)
</code></pre>
<p>如果你写过 C 或者 Objective-C 代码，那你应该很熟悉这种形式——在 Swift 中，这行代码就是一个完整的程序。你不需要为了输入输出或者字符串处理导入一个单独的库。全局作用域中的代码会被自动当做程序的入口点，所以你也不需要<code>main</code>函数。你同样不需要在每个语句结尾写上分号。</p>
<p>这个教程会通过一系列编程例子来让你对 Swift 有初步了解，如果你有什么不理解的地方也不用担心——任何本章介绍的内容都会在后面的章节中详细讲解。</p>
<blockquote>
<p>注意：</p>
<p>为了获得最好的体验，在 Xcode 当中使用代码预览功能。代码预览功能可以让你编辑代码并实时看到运行结果。</p>
</blockquote>
<p><a name="simple_values"></a></p>
<h2 id="-">简单值</h2>
<p>使用<code>let</code>来声明常量，使用<code>var</code>来声明变量。一个常量的值在编译时并不需要获取，但是你只能为它赋值一次。也就是说你可以用常量来表示这样一个值：你只需要决定一次，但是需要使用很多次。</p>
<pre><code class="lang-swift">    var myVariable = 42
    myVariable = 50
    let myConstant = 42
</code></pre>
<p>常量或者变量的类型必须和你赋给它们的值一样。然而，声明时类型是可选的，声明的同时赋值的话，编译器会自动推断类型。在上面的例子中，编译器推断出<code>myVariable</code>是一个整数（integer）因为它的初始值是整数。</p>
<p>如果初始值没有提供足够的信息（或者没有初始值），那你需要在变量后面声明类型，用冒号分割。</p>
<pre><code class="lang-swift">    let implicitInteger = 70
    let implicitDouble = 70.0
    let explicitDouble: Double = 70
</code></pre>
<blockquote>
<p>练习：</p>
<p>创建一个常量，显式指定类型为<code>Float</code>并指定初始值为4。</p>
</blockquote>
<p>值永远不会被隐式转换为其他类型。如果你需要把一个值转换成其他类型，请显式转换。</p>
<pre><code class="lang-swift">    let label = &quot;The width is&quot;
    let width = 94
    let widthLabel = label + String(width)
</code></pre>
<blockquote>
<p>练习：</p>
<p>删除最后一行中的<code>String</code>，错误提示是什么？</p>
</blockquote>
<p>有一种更简单的把值转换成字符串的方法：把值写到括号中，并且在括号之前写一个反斜杠。例如：</p>
<pre><code class="lang-swift">    let apples = 3
    let oranges = 5
    let appleSummary = &quot;I have \(apples) apples.&quot;
    let fruitSummary = &quot;I have \(apples + oranges) pieces of fruit.&quot;
</code></pre>
<blockquote>
<p>练习：</p>
<p>使用<code>\()</code>来把一个浮点计算转换成字符串，并加上某人的名字，和他打个招呼。</p>
</blockquote>
<p>使用方括号<code>[]</code>来创建数组和字典，并使用下标或者键（key）来访问元素。</p>
<pre><code class="lang-swift">    var shoppingList = [&quot;catfish&quot;, &quot;water&quot;, &quot;tulips&quot;, &quot;blue paint&quot;]
    shoppingList[1] = &quot;bottle of water&quot;
</code></pre>
<pre><code class="lang-swift">    var occupations = [
        &quot;Malcolm&quot;: &quot;Captain&quot;,
        &quot;Kaylee&quot;: &quot;Mechanic&quot;,
    ]
    occupations[&quot;Jayne&quot;] = &quot;Public Relations&quot;
</code></pre>
<p>要创建一个空数组或者字典，使用初始化语法。</p>
<pre><code class="lang-swift">    let emptyArray = String[]()
    let emptyDictionary = Dictionary&lt;String, Float&gt;()
</code></pre>
<p>如果类型信息可以被推断出来，你可以用<code>[]</code>和<code>[:]</code>来创建空数组和空字典——就像你声明变量或者给函数传参数的时候一样。</p>
<pre><code class="lang-swift">    shoppingList = []   // 去逛街并买点东西
</code></pre>
<p><a name="control_flow"></a></p>
<h2 id="-">控制流</h2>
<p>使用<code>if</code>和<code>switch</code>来进行条件操作，使用<code>for-in</code>、<code>for</code>、<code>while</code>和<code>do-while</code>来进行循环。包裹条件和循环变量括号可以省略，但是语句体的大括号是必须的。</p>
<pre><code class="lang-swift">    let individualScores = [75, 43, 103, 87, 12]
    var teamScore = 0
    for score in individualScores {
        if score &gt; 50 {
            teamScore += 3
        } else {
            teamScore += 1
        }
    }
    teamScore
</code></pre>
<p>在<code>if</code>语句中，条件必须是一个布尔表达式——这意味着像<code>if score { ... }</code>这样的代码将报错，而不会隐形地与 0 做对比。</p>
<p>你可以一起使用<code>if</code>和<code>let</code>来处理值缺失的情况。有些变量的值是可选的。一个可选的值可能是一个具体的值或者是<code>nil</code>，表示值缺失。在类型后面加一个问号来标记这个变量的值是可选的。</p>
<pre><code class="lang-swift">    var optionalString: String? = &quot;Hello&quot;
    optionalString == nil

    var optionalName: String? = &quot;John Appleseed&quot;
    var greeting = &quot;Hello!&quot;
    if let name = optionalName {
        greeting = &quot;Hello, \(name)&quot;
    }
</code></pre>
<blockquote>
<p>练习：</p>
<p>把<code>optionalName</code>改成<code>nil</code>，greeting会是什么？添加一个<code>else</code>语句，当<code>optionalName</code>是<code>nil</code>时给greeting赋一个不同的值。</p>
</blockquote>
<p>如果变量的可选值是<code>nil</code>，条件会判断为<code>false</code>，大括号中的代码会被跳过。如果不是<code>nil</code>，会将值赋给<code>let</code>后面的常量，这样代码块中就可以使用这个值了。</p>
<p><code>switch</code>支持任意类型的数据以及各种比较操作——不仅仅是整数以及测试相等。</p>
<pre><code class="lang-swift">    let vegetable = &quot;red pepper&quot;
    switch vegetable {
    case &quot;celery&quot;:
        let vegetableComment = &quot;Add some raisins and make ants on a log.&quot;
    case &quot;cucumber&quot;, &quot;watercress&quot;:
        let vegetableComment = &quot;That would make a good tea sandwich.&quot;
    case let x where x.hasSuffix(&quot;pepper&quot;):
        let vegetableComment = &quot;Is it a spicy \(x)?&quot;
    default:
        let vegetableComment = &quot;Everything tastes good in soup.&quot;
    }
</code></pre>
<blockquote>
<p>练习：</p>
<p>删除<code>default</code>语句，看看会有什么错误？</p>
</blockquote>
<p>运行<code>switch</code>中匹配到的子句之后，程序会退出<code>switch</code>语句，并不会继续向下运行，所以不需要在每个子句结尾写<code>break</code>。</p>
<p>你可以使用<code>for-in</code>来遍历字典，需要两个变量来表示每个键值对。</p>
<pre><code class="lang-swift">    let interestingNumbers = [
        &quot;Prime&quot;: [2, 3, 5, 7, 11, 13],
        &quot;Fibonacci&quot;: [1, 1, 2, 3, 5, 8],
        &quot;Square&quot;: [1, 4, 9, 16, 25],
    ]
    var largest = 0
    for (kind, numbers) in interestingNumbers {
        for number in numbers {
            if number &gt; largest {
                largest = number
            }
        }
    }
    largest
</code></pre>
<blockquote>
<p>练习：</p>
<p>添加另一个变量来记录哪种类型的数字是最大的。</p>
</blockquote>
<p>使用<code>while</code>来重复运行一段代码直到不满足条件。循环条件可以在开头也可以在结尾。</p>
<pre><code class="lang-swift">    var n = 2
    while n &lt; 100 {
        n = n * 2
    }
    n

    var m = 2
    do {
        m = m * 2
    } while m &lt; 100
    m
</code></pre>
<p>你可以在循环中使用<code>..</code>来表示范围，也可以使用传统的写法，两者是等价的：</p>
<pre><code class="lang-swift">    var firstForLoop = 0
    for i in 0..3 {
        firstForLoop += i
    }
    firstForLoop

    var secondForLoop = 0
    for var i = 0; i &lt; 3; ++i {
        secondForLoop += 1
    }
    secondForLoop
</code></pre>
<p>使用<code>..</code>创建的范围不包含上界，如果想包含的话需要使用<code>...</code>。</p>
<p><a name="functions_and_closures"></a></p>
<h2 id="-">函数和闭包</h2>
<p>使用<code>func</code>来声明一个函数，使用名字和参数来调用函数。使用<code>-&gt;</code>来指定函数返回值。</p>
<pre><code class="lang-swift">    func greet(name: String, day: String) -&gt; String {
        return &quot;Hello \(name), today is \(day).&quot;
    }
    greet(&quot;Bob&quot;, &quot;Tuesday&quot;)
</code></pre>
<blockquote>
<p>练习：</p>
<p>删除<code>day</code>参数，添加一个参数来表示今天吃了什么午饭。</p>
</blockquote>
<p>使用一个元组来返回多个值。</p>
<pre><code class="lang-swift">    func getGasPrices() -&gt; (Double, Double, Double) {
        return (3.59, 3.69, 3.79)
    }
    getGasPrices()
</code></pre>
<p>函数的参数数量是可变的，用一个数组来获取它们：</p>
<pre><code class="lang-swift">    func sumOf(numbers: Int...) -&gt; Int {
        var sum = 0
        for number in numbers {
            sum += number
        }
        return sum
    }
    sumOf()
    sumOf(42, 597, 12)
</code></pre>
<blockquote>
<p>练习：</p>
<p>写一个计算参数平均值的函数。</p>
</blockquote>
<p>函数可以嵌套。被嵌套的函数可以访问外侧函数的变量，你可以使用嵌套函数来重构一个太长或者太复杂的函数。</p>
<pre><code class="lang-swift">    func returnFifteen() -&gt; Int {
        var y = 10
        func add() {
            y += 5
        }
        add()
        return y
    }
    returnFifteen()
</code></pre>
<p>函数是第一等类型，这意味着函数可以作为另一个函数的返回值。</p>
<pre><code class="lang-swift">    func makeIncrementer() -&gt; (Int -&gt; Int) {
        func addOne(number: Int) -&gt; Int {
            return 1 + number
        }
        return addOne
    }
    var increment = makeIncrementer()
    increment(7)
</code></pre>
<p>函数也可以当做参数传入另一个函数。</p>
<pre><code class="lang-swift">    func hasAnyMatches(list: Int[], condition: Int -&gt; Bool) -&gt; Bool {
        for item in list {
            if condition(item) {
                return true
            }
        }
        return false
    }
    func lessThanTen(number: Int) -&gt; Bool {
        return number &lt; 10
    }
    var numbers = [20, 19, 7, 12]
    hasAnyMatches(numbers, lessThanTen)
</code></pre>
<p>函数实际上是一种特殊的闭包，你可以使用<code>{}</code>来创建一个匿名闭包。使用<code>in</code>将参数和返回值类型声明与闭包函数体进行分离。</p>
<pre><code class="lang-swift">    numbers.map({
        (number: Int) -&gt; Int in
        let result = 3 * number
        return result
        })
</code></pre>
<blockquote>
<p>练习：</p>
<p>重写闭包，对所有奇数返回 0.</p>
</blockquote>
<p>有很多种创建闭包的方法。如果一个闭包的类型已知，比如作为一个回调函数，你可以忽略参数的类型和返回值。单个语句闭包会把它语句的值当做结果返回。</p>
<pre><code class="lang-swift">    numbers.map({ number in 3 * number })
</code></pre>
<p>你可以通过参数位置而不是参数名字来引用参数——这个方法在非常短的闭包中非常有用。当一个闭包作为最后一个参数传给一个函数的时候，它可以直接跟在括号后面。</p>
<pre><code class="lang-swift">    sort([1, 5, 3, 12, 2]) { $0 &gt; $1 }
</code></pre>
<p><a name="objects_and_classes"></a></p>
<h2 id="-">对象和类</h2>
<p>使用<code>class</code>和类名来创建一个类。类中属性的声明和常量、变量声明一样，唯一的区别就是它们的上下文是类。同样，方法和函数声明也一样。</p>
<pre><code class="lang-swift">    class Shape {
        var numberOfSides = 0
        func simpleDescription() -&gt; String {
            return &quot;A shape with \(numberOfSides) sides.&quot;
        }
    }
</code></pre>
<blockquote>
<p>练习：</p>
<p>使用<code>let</code>添加一个常量属性，再添加一个接收一个参数的方法。</p>
</blockquote>
<p>要创建一个类的实例，在类名后面加上括号。使用点语法来访问实例的属性和方法。</p>
<pre><code class="lang-swift">    var shape = Shape()
    shape.numberOfSides = 7
    var shapeDescription = shape.simpleDescription()
</code></pre>
<p>这个版本的<code>Shape</code>类缺少了一些重要的东西：一个构造函数来初始化类实例。使用<code>init</code>来创建一个构造器。</p>
<pre><code class="lang-swift">    class NamedShape {
        var numberOfSides: Int = 0
        var name: String

        init(name: String) {
            self.name = name
        }

        func simpleDescription() -&gt; String {
            return &quot;A shape with \(numberOfSides) sides.&quot;
        }
    }
</code></pre>
<p>注意<code>self</code>被用来区别实例变量。当你创建实例的时候，像传入函数参数一样给类传入构造器的参数。每个属性都需要赋值——无论是通过声明（就像<code>numberOfSides</code>）还是通过构造器（就像<code>name</code>）。</p>
<p>如果你需要在删除对象之前进行一些清理工作，使用<code>deinit</code>创建一个析构函数。</p>
<p>子类的定义方法是在它们的类名后面加上父类的名字，用冒号分割。创建类的时候并不需要一个标准的根类，所以你可以忽略父类。</p>
<p>子类如果要重写父类的方法的话，需要用<code>override</code>标记——如果没有添加<code>override</code>就重写父类方法的话编译器会报错。编译器同样会检测<code>override</code>标记的方法是否确实在父类中。</p>
<pre><code class="lang-swift">    class Square: NamedShape {
        var sideLength: Double

        init(sideLength: Double, name: String) {
            self.sideLength = sideLength
            super.init(name: name)
            numberOfSides = 4
        }

        func area() -&gt;  Double {
            return sideLength * sideLength
        }

        override func simpleDescription() -&gt; String {
            return &quot;A square with sides of length \(sideLength).&quot;
        }
    }
    let test = Square(sideLength: 5.2, name: &quot;my test square&quot;)
    test.area()
    test.simpleDescription()
</code></pre>
<blockquote>
<p>练习：</p>
<p>创建<code>NamedShape</code>的另一个子类<code>Circle</code>，构造器接收两个参数，一个是半径一个是名称，实现<code>area</code>和<code>describe</code>方法。</p>
</blockquote>
<p>属性可以有 getter 和 setter 。</p>
<pre><code class="lang-swift">    class EquilateralTriangle: NamedShape {
        var sideLength: Double = 0.0

        init(sideLength: Double, name: String) {
            self.sideLength = sideLength
            super.init(name: name)
            numberOfSides = 3
        }

        var perimeter: Double {
        get {
            return 3.0 * sideLength
        }
        set {
                    sideLength = newValue / 3.0
        }
        }

        override func simpleDescription() -&gt; String {
            return &quot;An equilateral triagle with sides of length \(sideLength).&quot;
        }
    }
    var triangle = EquilateralTriangle(sideLength: 3.1, name: &quot;a triangle&quot;)
    triangle.perimeter
    triangle.perimeter = 9.9
    triangle.sideLength
</code></pre>
<p>在<code>perimeter</code>的 setter 中，新值的名字是<code>newValue</code>。你可以在<code>set</code>之后显式的设置一个名字。</p>
<p>注意<code>EquilateralTriangle</code>类的构造器执行了三步：</p>
<ol>
<li>设置子类声明的属性值</li>
<li>调用父类的构造器</li>
<li>改变父类定义的属性值。其他的工作比如调用方法、getters和setters也可以在这个阶段完成。</li>
</ol>
<p>如果你不需要计算属性但是需要在设置一个新值之前运行一些代码，使用<code>willSet</code>和<code>didSet</code>。</p>
<p>比如，下面的类确保三角形的边长总是和正方形的边长相同。</p>
<pre><code class="lang-swift">    class TriangleAndSquare {
        var triangle: EquilateralTriangle {
        willSet {
            square.sideLength = newValue.sideLength
        }
        }
        var square: Square {
        willSet {
            triangle.sideLength = newValue.sideLength
        }
        }
        init(size: Double, name: String) {
            square = Square(sideLength: size, name: name)
            triangle = EquilateralTriangle(sideLength: size, name: name)
        }
    }
    var triangleAndSquare = TriangleAndSquare(size: 10, name: &quot;another test shape&quot;)
    triangleAndSquare.square.sideLength
    triangleAndSquare.triangle.sideLength
    triangleAndSquare.square = Square(sideLength: 50, name: &quot;larger square&quot;)
    triangleAndSquare.triangle.sideLength
</code></pre>
<p>类中的方法和一般的函数有一个重要的区别，函数的参数名只在函数内部使用，但是方法的参数名需要在调用的时候显式说明（除了第一个参数）。默认情况下，方法的参数名和它在方法内部的名字一样，不过你也可以定义第二个名字，这个名字被用在方法内部。</p>
<pre><code class="lang-swift">    class Counter {
        var count: Int = 0
        func incrementBy(amount: Int, numberOfTimes times: Int) {
            count += amount * times
        }
    }
    var counter = Counter()
    counter.incrementBy(2, numberOfTimes: 7)
</code></pre>
<p>处理变量的可选值时，你可以在操作（比如方法、属性和子脚本）之前加<code>?</code>。如果<code>?</code>之前的值是<code>nil</code>，<code>?</code>后面的东西都会被忽略，并且整个表达式返回<code>nil</code>。否则，<code>?</code>之后的东西都会被运行。在这两种情况下，整个表达式的值也是一个可选值。</p>
<pre><code class="lang-swift">    let optionalSquare: Square? = Square(sideLength: 2.5, name: &quot;optional square&quot;)
    let sideLength = optionalSquare?.sideLength
</code></pre>
<p><a name="enumerations_and_structure"></a></p>
<h2 id="-">枚举和结构体</h2>
<p>使用<code>enum</code>来创建一个枚举。就像类和其他所有命名类型一样，枚举可以包含方法。</p>
<pre><code class="lang-swift">    enum Rank: Int {
        case Ace = 1
        case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
        case Jack, Queen, King
        func simpleDescription() -&gt; String {
            switch self {
            case .Ace:
                return &quot;ace&quot;
            case .Jack:
                return &quot;jack&quot;
            case .Queen:
                return &quot;queen&quot;
            case .King:
                return &quot;king&quot;
            default:
                return String(self.toRaw())
            }
        }
    }
    let ace = Rank.Ace
    let aceRawValue = ace.toRaw()
</code></pre>
<blockquote>
<p>练习：</p>
<p>写一个函数，通过比较它们的原始值来比较两个<code>Rank</code>值。</p>
</blockquote>
<p>在上面的例子中，枚举原始值的类型是<code>Int</code>，所以你只需要设置第一个原始值。剩下的原始值会按照顺序赋值。你也可以使用字符串或者浮点数作为枚举的原始值。</p>
<p>使用<code>toRaw</code>和<code>fromRaw</code>函数来在原始值和枚举值之间进行转换。</p>
<pre><code class="lang-swift">    if let convertedRank = Rank.fromRaw(3) {
        let threeDescription = convertedRank.simpleDescription()
    }
</code></pre>
<p>枚举的成员值是实际值，并不是原始值的另一种表达方法。实际上，如果原始值没有意义，你不需要设置。</p>
<pre><code class="lang-swift">    enum Suit {
        case Spades, Hearts, Diamonds, Clubs
        func simpleDescription() -&gt; String {
            switch self {
            case .Spades:
                return &quot;spades&quot;
            case .Hearts:
                return &quot;hearts&quot;
            case .Diamonds:
                return &quot;diamonds&quot;
            case .Clubs:
                return &quot;clubs&quot;
            }
        }

    }
    let hearts = Suit.Hearts
    let heartsDescription = hearts.simpleDescription()
</code></pre>
<blockquote>
<p>练习：</p>
<p>给<code>Suit</code>添加一个<code>color</code>方法，对<code>spades</code>和<code>clubs</code>返回“black”，对<code>hearts</code>和<code>diamonds</code>返回“red”。</p>
</blockquote>
<p>注意，有两种方式可以引用<code>Hearts</code>成员：给<code>hearts</code>常量赋值时，枚举成员<code>Suit.Hearts</code>需要用全名来引用，因为常量没有显式指定类型。在<code>switch</code>里，枚举成员使用缩写<code>.Hearts</code>来引用，因为<code>self</code>的值已经知道是一个<code>suit</code>。已知变量类型的情况下你可以使用缩写。</p>
<p>使用<code>struct</code>来创建一个结构体。结构体和类有很多相同的地方，比如方法和构造器。它们之间最大的一个区别就是
结构体是传值，类是传引用。</p>
<pre><code class="lang-swift">    struct Card {
        var rank: Rank
        var suit: Suit
        func simpleDescription() -&gt; String {
            return &quot;The \(rank.simpleDescription()) of \
            (suit.simpleDescription())&quot;
        }
    }
    let threeOfSpades = Card(rank: .Three, suit: .Spades)
    let threeOfSpadesDescription = threeOfSpades.simpleDescription()
</code></pre>
<blockquote>
<p>练习：</p>
<p>给<code>Card</code>添加一个方法，创建一副完整的扑克牌并把每张牌的 rank 和 suit 对应起来。</p>
</blockquote>
<p>一个枚举成员的实例可以有实例值。相同枚举成员的实例可以有不同的值。创建实例的时候传入值即可。实例值和原始值是不同的：枚举成员的原始值对于所有实例都是相同的，而且你是在定义枚举的时候设置原始值。</p>
<p>例如，考虑从服务器获取日出和日落的时间。服务器会返回正常结果或者错误信息。</p>
<pre><code class="lang-swift">    enum ServerResponse {
        case Result(String, String)
        case Error(String)
    }

    let success = ServerResponse.Result(&quot;6:00 am&quot;, &quot;8:09 pm&quot;)
    let failure = ServerResponse.Error(&quot;Out of cheese.&quot;)

    switch success {
    case let .Result(sunrise, sunset):
        let serverResponse = &quot;Sunrise is at \(sunrise) and sunset is at \(sunset).&quot;
    case let .Error(error):
        let serverResponse = &quot;Failure...  \(error)&quot;
    }
</code></pre>
<blockquote>
<p>练习：</p>
<p>给<code>ServerResponse</code>和<code>switch</code>添加第三种情况。</p>
</blockquote>
<p>注意如何从<code>ServerResponse</code>中提取日升和日落时间。</p>
<p><a name="protocols_and_extensions"></a></p>
<h2 id="-">接口和扩展</h2>
<p>使用<code>protocol</code>来声明一个接口。</p>
<pre><code class="lang-swift">    protocol ExampleProtocol {
        var simpleDescription: String { get }
        mutating func adjust()
    }
</code></pre>
<p>类、枚举和结构体都可以实现接口。</p>
<pre><code class="lang-swift">    class SimpleClass: ExampleProtocol {
        var simpleDescription: String = &quot;A very simple class.&quot;
        var anotherProperty: Int = 69105
        func adjust() {
            simpleDescription += &quot;  Now 100% adjusted.&quot;
        }
    }
    var a = SimpleClass()
    a.adjust()
    let aDescription = a.simpleDescription

    struct SimpleStructure: ExampleProtocol {
        var simpleDescription: String = &quot;A simple structure&quot;
        mutating func adjust() {
            simpleDescription += &quot; (adjusted)&quot;
        }
    }
    var b = SimpleStructure()
    b.adjust()
    let bDescription = b.simpleDescription
</code></pre>
<blockquote>
<p>练习：</p>
<p>写一个实现这个接口的枚举。</p>
</blockquote>
<p>注意声明<code>SimpleStructure</code>时候<code>mutating</code>关键字用来标记一个会修改结构体的方法。<code>SimpleClass</code>的声明不需要标记任何方法因为类中的方法经常会修改类。</p>
<p>使用<code>extension</code>来为现有的类型添加功能，比如添加一个计算属性的方法。你可以使用扩展来给任意类型添加协议，甚至是你从外部库或者框架中导入的类型。</p>
<pre><code class="lang-swift">    extension Int: ExampleProtocol {
        var simpleDescription: String {
        return &quot;The number \(self)&quot;
        }
        mutating func adjust() {
            self += 42
        }
    }
    7.simpleDescription
</code></pre>
<blockquote>
<p>练习：</p>
<p>给<code>Double</code>类型写一个扩展，添加<code>absoluteValue</code>功能。</p>
</blockquote>
<p>你可以像使用其他命名类型一样使用接口名——例如，创建一个有不同类型但是都实现一个接口的对象集合。当你处理类型是接口的值时，接口外定义的方法不可用。</p>
<pre><code class="lang-swift">    let protocolValue: ExampleProtocol = a
    protocolValue.simpleDescription
    // protocolValue.anotherProperty  // Uncomment to see the error
</code></pre>
<p>即使<code>protocolValue</code>变量运行时的类型是<code>simpleClass</code>，编译器会把它的类型当做<code>ExampleProtocol</code>。这表示你不能调用类在它实现的接口之外实现的方法或者属性。</p>
<p><a name="generics"></a></p>
<h2 id="-">泛型</h2>
<p>在尖括号里写一个名字来创建一个泛型函数或者类型。</p>
<pre><code class="lang-swift">    func repeat&lt;ItemType&gt;(item: ItemType, times: Int) -&gt; ItemType[] {
        var result = ItemType[]()
        for i in 0..times {
            result += item
        }
        return result
    }
    repeat(&quot;knock&quot;, 4)
</code></pre>
<p>你也可以创建泛型类、枚举和结构体。</p>
<pre><code class="lang-swift">    // Reimplement the Swift standard library&#39;s optional type
    enum OptionalValue&lt;T&gt; {
        case None
        case Some(T)
    }
    var possibleInteger: OptionalValue&lt;Int&gt; = .None
    possibleInteger = .Some(100)
</code></pre>
<p>在类型名后面使用<code>where</code>来指定一个需求列表——例如，要限定实现一个协议的类型，需要限定两个类型要相同，或者限定一个类必须有一个特定的父类。</p>
<pre><code class="lang-swift">    func anyCommonElements &lt;T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element&gt; (lhs: T, rhs: U) -&gt; Bool {
        for lhsItem in lhs {
            for rhsItem in rhs {
                if lhsItem == rhsItem {
                    return true
                }
            }
        }
        return false
    }
    anyCommonElements([1, 2, 3], [3])
</code></pre>
<blockquote>
<p>练习：</p>
<p>修改<code>anyCommonElements</code>函数来创建一个函数，返回一个数组，内容是两个序列的共有元素。</p>
</blockquote>
<p>简单起见，你可以忽略<code>where</code>，只在冒号后面写接口或者类名。<code>&lt;T: Equatable&gt;</code>和<code>&lt;T where T: Equatable&gt;</code>是等价的。</p>

                    
                    </section>
                
                </div>
            </div>
        </div>

        
        <a href="../chapter1/01_swift.html" class="navigation navigation-prev " aria-label="Previous page: 关于 Swift"><i class="fa fa-angle-left"></i></a>
        
        
        <a href="../chapter2/chapter2.html" class="navigation navigation-next " aria-label="Next page: Swift 教程"><i class="fa fa-angle-right"></i></a>
        
    </div>
</div>

        

        <script src="http://cdn.bootcss.com/ace/1.1.3/ace.js"></script>
        <script src="http://cdn.bootcss.com/ace/1.1.3/mode-javascript.js"></script>
        <script src="../gitbook/jsrepl/jsrepl.js" id="jsrepl-script"></script>
        <script src="../gitbook/app.js"></script>
        

    
    <script src="../gitbook/plugins/gitbook-plugin-mixpanel/plugin.js"></script>
    

    
    <script src="http://cdn.mathjax.org/mathjax/2.0-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    

    
    <script src="../gitbook/plugins/gitbook-plugin-mathjax/plugin.js"></script>
    

<script>
require(["gitbook"], function(gitbook) {
    var config = {};
    gitbook.start(config);
});
</script>

        
    <script src="http://yandex.st/highlightjs/8.0/styles/default.min.css"></script><script src="http://yandex.st/highlightjs/8.0/highlight.min.js"></script><script text="javascript">$('pre code').each(function(i, block) {hljs.highlightBlock(block);});</script></body>
    
</html>
